{ <description>

  Copyright (C) 2011 Anton A. Lindeberg lindeberg.a@gmail.com

  This source is free software; you can redistribute it and/or modify it under
  the terms of the GNU General Public License as published by the Free
  Software Foundation; either version 2 of the License, or (at your option)
  any later version.

  This code is distributed in the hope that it will be useful, but WITHOUT ANY
  WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
  details.

  A copy of the GNU General Public License is available on the World Wide Web
  at <http://www.gnu.org/copyleft/gpl.html>. You can also obtain it by writing
  to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
  MA 02111-1307, USA.
}

unit uMain;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, Menus,
  ComCtrls, ExtCtrls, StdCtrls, DBGrids, Buttons, DBCtrls,
  SynEdit,
  SynHighlighterSQL, uEditTabSheet, upgeditor, sslib, SynCompletion,
  SynHighlighterAny, ZConnection, ZDataset, types, DB, u_optionsfrm, IniFiles,
  uoptions, Clipbrd, LCLIntf,  uTPrjManager, LCLType  ;

type

  { Tf_main }

  Tf_main = class(TForm)
    ds: TDatasource;
    Edit1: TEdit;
    edit_find: TEdit;
    GroupBox1: TGroupBox;
    ImageList: TImageList;
    lv_prj: TListView;
    MainMenu: TMainMenu;
    memo_notes: TMemo;
    MenuItem1: TMenuItem;
    mEdiOpt: TMenuItem;
    MenuItem10: TMenuItem;
    MenuItem11: TMenuItem;
    MenuItem12: TMenuItem;
    MenuItem14: TMenuItem;
    MenuItem15: TMenuItem;
    MenuItem17: TMenuItem;
    MenuItem18: TMenuItem;
    MenuItem19: TMenuItem;
    pm_dbe1: TPopupMenu;
    pm_dbeEditData1: TMenuItem;
    pm_dbeNew1: TMenuItem;
    pm_dbeScrCreate1: TMenuItem;
    pm_dbeScrDELETE1: TMenuItem;
    pm_dbeScrINSERT1: TMenuItem;
    pm_dbeScrNewView1: TMenuItem;
    pm_dbeScrQueryData: TMenuItem;
    MenuItem16: TMenuItem;
    pm_dbeEditData: TMenuItem;
    pm_dbeScrDELETE: TMenuItem;
    pm_dbeScrCreate: TMenuItem;
    pm_dbeScrQueryData1: TMenuItem;
    pm_dbeScrSELECT1: TMenuItem;
    pm_dbeScrUPDATE: TMenuItem;
    pm_dbeScrINSERT: TMenuItem;
    pm_dbeScrSELECT: TMenuItem;
    pm_dbeScrUPDATE1: TMenuItem;
    pm_dbe_refresh1: TMenuItem;
    pm_dbe_Scr: TMenuItem;
    pm_dbeNew: TMenuItem;
    pm_dbe_refresh: TMenuItem;
    MenuItem13: TMenuItem;
    mViewFS: TMenuItem;
    pm_dbe_Scr1: TMenuItem;
    pm_prjOpen: TMenuItem;
    pm__prjRm: TMenuItem;
    pm_PrjAdd: TMenuItem;
    pm_tabAdd2Prj: TMenuItem;
    pm_gridExport: TMenuItem;
    pm_msgClear: TMenuItem;
    pm_msgCopyAll: TMenuItem;
    pm_msgCopy: TMenuItem;
    mRunCommit: TMenuItem;
    mRunRollback: TMenuItem;
    MenuItem8: TMenuItem;
    mRunStop: TMenuItem;
    mRunExecute: TMenuItem;
    mRun: TMenuItem;
    MenuItem9: TMenuItem;
    oDlg: TOpenDialog;
    pm_EdtPaste: TMenuItem;
    pm_EdtCopy: TMenuItem;
    pm_EdtCut: TMenuItem;
    pm_TabClose: TMenuItem;
    mHelpabout: TMenuItem;
    mHelpHelp: TMenuItem;
    MenuItem2: TMenuItem;
    MenuItem3: TMenuItem;
    MenuItem4: TMenuItem;
    mEdit: TMenuItem;
    mEditUndo: TMenuItem;
    mEditRedo: TMenuItem;
    MenuItem5: TMenuItem;
    mEditCut: TMenuItem;
    mEditCopy: TMenuItem;
    mEditPaste: TMenuItem;
    MenuItem6: TMenuItem;
    mEditSearch: TMenuItem;
    mEditGoToString: TMenuItem;
    MenuItem7: TMenuItem;
    mHelpBags: TMenuItem;
    mHelp: TMenuItem;
    mProjectClose: TMenuItem;
    mRPFiles: TMenuItem;
    mProjectRecent: TMenuItem;
    mProjectOpen: TMenuItem;
    mView: TMenuItem;
    mProjectNew: TMenuItem;
    mProject: TMenuItem;
    mFileConnectionClose: TMenuItem;
    mFileExit: TMenuItem;
    mFilePrint: TMenuItem;
    mFileOpen: TMenuItem;
    mFileNew: TMenuItem;
    mFileNewFile: TMenuItem;
    mFileCloseAll: TMenuItem;
    mFileClose: TMenuItem;
    mFileConnection: TMenuItem;
    mFileSaveAll: TMenuItem;
    mRFiles: TMenuItem;
    mFileRecentFiles: TMenuItem;
    mFileSaveAs: TMenuItem;
    mFileSave: TMenuItem;
    mFile: TMenuItem;
    pc_right: TPageControl;
    pc_left: TPageControl;
    pm_Tab: TPopupMenu;
    pm_Edt: TPopupMenu;
    frDlg: TReplaceDialog;
    pm_msg: TPopupMenu;
    pm_grid: TPopupMenu;
    pm_prj: TPopupMenu;
    pm_dbe: TPopupMenu;
    PopupMenu1: TPopupMenu;
    sDlgExp: TSaveDialog;
    sDlg: TSaveDialog;
    SpeedButton1: TSpeedButton;
    Splitter1: TSplitter;
    Splitter3: TSplitter;
    StatusBar: TStatusBar;
    SynAutoComplete1: TSynAutoComplete;
    tv_db: TTreeView;
    ToolBar: TToolBar;
    ToolBar1: TToolBar;
    ToolButton1: TToolButton;
    ToolButton2: TToolButton;
    ToolButton3: TToolButton;
    ToolButton4: TToolButton;
    ToolButton5: TToolButton;
    ToolButton6: TToolButton;
    tbtRun: TToolButton;
    tbtStop: TToolButton;
    ToolButton9: TToolButton;
    ts_dbexplorer: TTabSheet;
    ts_ProjectExplorer: TTabSheet;
    zConn: TZConnection;
    zQyery: TZQuery;

    procedure Edit1Change(Sender: TObject);
    procedure Edit1Click(Sender: TObject);
    procedure Edit1EditingDone(Sender: TObject);
    procedure edit_findKeyDown(Sender: TObject; var Key: word; Shift: TShiftState);
    procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
    procedure FormCloseQuery(Sender: TObject; var CanClose: boolean);
    procedure FormCreate(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure frDlgFind(Sender: TObject);
    procedure frDlgReplace(Sender: TObject);
    procedure mEdiOptClick(Sender: TObject);

    procedure mEditSearchClick(Sender: TObject);
    procedure mFileCloseAllClick(Sender: TObject);
    procedure mFileCloseClick(Sender: TObject);
    procedure mFileConnectionClick(Sender: TObject);
    procedure mFileConnectionCloseClick(Sender: TObject);
    procedure mFileExitClick(Sender: TObject);
    procedure mFileNewClick(Sender: TObject);
    procedure mFileOpenClick(Sender: TObject);
    procedure mFileSaveAllClick(Sender: TObject);
    procedure mFileSaveAsClick(Sender: TObject);
    procedure mFileSaveClick(Sender: TObject);
    procedure mHelpaboutClick(Sender: TObject);
    procedure mProjectCloseClick(Sender: TObject);
    procedure mProjectNewClick(Sender: TObject);
    procedure mProjectOpenClick(Sender: TObject);
    procedure mRunExecuteClick(Sender: TObject);
    procedure mRunStopClick(Sender: TObject);
    procedure mServiceIdeParClick(Sender: TObject);
    procedure mViewFSClick(Sender: TObject);
    procedure pc_rightChange(Sender: TObject);
    procedure pc_rightCloseTabClicked(Sender: TObject);
    procedure pc_rightContextPopup(Sender: TObject; MousePos: TPoint;
      var Handled: boolean);
    procedure pc_rightMouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: integer);
    procedure pm_dbePopup(Sender: TObject);
    procedure pm_dbe_refreshClick(Sender: TObject);
    procedure pm_gridExportClick(Sender: TObject);
    procedure pm_gridPopup(Sender: TObject);
    procedure pm_msgCopyAllClick(Sender: TObject);
    procedure pm_EdtCopyClick(Sender: TObject);
    procedure pm_EdtCutClick(Sender: TObject);
    procedure pm_EdtPasteClick(Sender: TObject);
    procedure pm_msgClearClick(Sender: TObject);
    procedure pm_msgCopyClick(Sender: TObject);
    procedure pm_PrjAddClick(Sender: TObject);
    procedure pm_prjOpenClick(Sender: TObject);
    procedure pm_tabAdd2PrjClick(Sender: TObject);
    procedure pm_TabCloseClick(Sender: TObject);
    procedure CreateTab(Sender: TObject; Mode: TModeCreate; RO: boolean; FileName: string);
    procedure pm__prjRmClick(Sender: TObject);
    procedure SetLng();
    procedure CreateIni();
    procedure ReadIni();
    procedure SetOptions();
    procedure OpenProj(Sender: TObject; FileName: String; Mode: TModeCreate);
    function Connect(): boolean;
    procedure GetDbObject();
    procedure tv_dbDblClick(Sender: TObject);
    procedure RecentLoad();
    procedure RecentOpen(Sender: TObject);
    procedure RecentAdd(FileName: string);
    function SheetExist(FileName:string):boolean;

    //dbo
    procedure GetSelectSQL(Sender:TObject);
    procedure GetDef_funct(Sender: TObject);
    procedure GetDefTg(Sender: TObject);



    procedure SQLCompletionCreate(Sender: TObject);


    procedure SQLComplKeyPress(Sender: TObject; var Key: char);


  private
    { private declarations }
       SQLCompletion: TSynCompletion;
       procedure DoSearchPosition(var APosition: integer);
  public
    { public declarations }
  end;

var
  f_main: Tf_main;
  rFiles: TStringList; //recent files
  ActiveTab: integer;
  textexit: boolean;
  FileName: string;
  Language: string;
  path:     string;  //user path
  opt: TOptions;
  PrjManager: TPrjManager;
  Highlighter: TSynSQLSyn;
  SQLComplList: TStringlist; //SQL completelist

  //Временно
  Tt: Integer;

implementation

uses uloginprmpt, unewprgfrm, uaboutfrm, MouseAndKeyInput;

{$R *.lfm}

{ Tf_main }

procedure Tf_main.mFileExitClick(Sender: TObject);
begin
  Close();
end;

procedure Tf_main.mFileNewClick(Sender: TObject);
begin
  CreateTab(Sender, mNew, False, '');
end;

procedure Tf_main.mFileOpenClick(Sender: TObject);
begin
  if oDlg.Execute then
   begin
    if SheetExist(oDlg.FileName) = true then Exit;
    CreateTab(Sender, mOpen, False, oDlg.FileName);
   end;
end;

procedure Tf_main.mFileSaveAllClick(Sender: TObject); //Save all
var
  i: integer;
begin
  for i := 0 to pc_right.ControlCount - 1 do
    if (pc_right.Controls[i] is TEditTabSheet) and
      (TEditTabSheet(pc_right.Controls[i]).Edt.Modified = True) then
    begin
      if TEditTabSheet(pc_right.Controls[i]).Edt.FileName = '' then
      begin
        if sDlg.Execute then
        begin
          TEditTabSheet(pc_right.Controls[i]).Edt.Lines.SaveToFile(
            sDlg.FileName);
          TEditTabSheet(pc_right.Controls[i]).Edt.FileName := sDlg.FileName;
        end;
      end
      else
        TEditTabSheet(pc_right.Controls[i]).Edt.Lines.SaveToFile(
          TEditTabSheet(pc_right.Controls[i]).Edt.FileName);
    end;

end;

procedure Tf_main.mFileSaveAsClick(Sender: TObject);
var
  i: integer;
begin
  //Save as...
  for i := 0 to pc_right.ActivePage.ControlCount - 1 do
    if pc_right.ActivePage.Controls[I] is tPgEditor then
    begin

      if sDlg.Execute then
      begin
        tPgEditor(pc_right.ActivePage.Controls[I]).Lines.SaveToFile(sDlg.FileName);
        tPgEditor(pc_right.ActivePage.Controls[I]).FileName := sDlg.FileName;
        pc_right.ActivePage.Caption := ExtractFileName(sDlg.FileName);
      end;
    end;
end;


procedure Tf_main.mFileSaveClick(Sender: TObject);  //Save;
var
  i: integer;
begin
  if pc_right.PageCount<1 then exit;
  for I := 0 to pc_right.ActivePage.ControlCount - 1 do
    if pc_right.ActivePage.Controls[I] is tPgEditor then
    begin
      if tPgEditor(pc_right.ActivePage.Controls[I]).FileName = '' then
      begin
        if sDlg.Execute then
        begin
          tPgEditor(pc_right.ActivePage.Controls[I]).Lines.SaveToFile(sDlg.FileName);
          tPgEditor(pc_right.ActivePage.Controls[I]).FileName := sDlg.FileName;;
        end;
      end
      else
        tPgEditor(pc_right.ActivePage.Controls[I]).Lines.SaveToFile(
        tPgEditor(pc_right.ActivePage.Controls[I]).FileName);
    end;
end;

procedure Tf_main.FormShow(Sender: TObject);
begin

end;

procedure Tf_main.frDlgFind(Sender: TObject);
var
  SelPos, X, i: integer;
  s, textE: string;
  Tab: TeditTabSheet;
label
  1;
begin
  if pc_right.PageCount < 1 then
    Exit;
  Tab := (pc_right.ActivePage as TeditTabSheet);
  if frDown in frDlg.Options then
    Tab.Edt.SelStart := Tab.Edt.SelStart + (Tab.Edt.SelEnd - Tab.Edt.SelStart);
  textE := Tab.Edt.Text;
  X := Tab.Edt.SelStart + 1;
  if frDown in frDlg.Options then
    textE := Copy(textE, X, Length(textE) - X + 1)
  else
    textE := Copy(textE, 0, X - 1);
  s := frDlg.FindText;
  if frDown in FrDlg.Options then
    //Serch Down
  begin
    SelPos := Pos(s, textE);
    if SelPos > 0 then
    begin
      Tab.Edt.SelStart := SelPos + X - 1;
      Tab.Edt.Selend := (SelPos + X - 1) + length(s);
    end
    else;
   end
  else
   //Search Up
  begin
    for i := length(textE) - length(s) downto 1 do
      if copy(textE, i, length(s)) = s then
      begin
        Tab.Edt.SelStart := i;
        Tab.Edt.SelEnd := (i) + Length(s);
        goto 1;
      end;
     1: ;
  end;

end;

procedure Tf_main.frDlgReplace(Sender: TObject);
var
  Tab: TeditTabSheet;
begin
  if pc_right.PageCount < 1 then
    Exit;
  Tab := (pc_right.ActivePage as TeditTabSheet);
  with Sender as TReplaceDialog do
    while True do
    begin
      if Tab.Edt.SelText <> FindText then
        frDlgFind(Sender);
      if (Tab.Edt.SelEnd - tab.Edt.SelStart) = 0 then
        Break;
      Tab.Edt.SelText := ReplaceText;
      if not (frReplaceAll in Options) then
        Break;
    end;
end;

procedure Tf_main.mEdiOptClick(Sender: TObject);
begin
  f_options.Show;
end;




procedure Tf_main.mEditSearchClick(Sender: TObject);
begin
  frDlg.Execute;
end;


procedure Tf_main.mFileCloseAllClick(Sender: TObject);
var i:  integer;
begin
   for I := 0 to pc_right.ControlCount  - 1 do
     begin
       mFileCloseClick(Sender);
     end;
end;

procedure Tf_main.mFileCloseClick(Sender: TObject);
begin
  if pc_right.PageCount<1 then Exit;
  pc_rightCloseTabClicked(pc_right.ActivePage);
end;

procedure Tf_main.mFileConnectionClick(Sender: TObject);
begin
   if Connect=True then
      begin
        mRunExecute.Enabled:=True;
        mRunStop.Enabled:=True;
        tbtStop.Enabled:=True;
        tbtRun.Enabled:=True;
        Caption:='PL/pgSQL Studio'+' '+zconn.Database+'@'+zconn.HostName+':'+
        IntToStr(zconn.Port);
       end else
       begin
        mRunExecute.Enabled:=False;
        mRunStop.Enabled:=False;
        tbtStop.Enabled:=False;
        tbtRun.Enabled:=False;
       end;
end;

procedure Tf_main.mFileConnectionCloseClick(Sender: TObject);
begin
  if zconn.Connected=True then
    begin
      zconn.Connected:=False;
      mRunExecute.Enabled:=False;
      mRunStop.Enabled:=False;
      tbtStop.Enabled:=False;
      tbtRun.Enabled:=False;
    end;
end;

procedure Tf_main.FormCreate(Sender: TObject);
begin
  ReadIni();
  {$ifdef Windows}
  pc_right.PopupMenu := pm_tab;
  {$endif}
  SetLng();
  SetOptions();
  mFileConnectionClick(Sender);

  pm_tabAdd2Prj.Visible:=False;
  if ParamCount>0 then   CreateTab(Sender, mOpen, False, ParamStr(1));
  Edit1.Text:=Localize('Search...');
  RecentLoad();
  SQLCompletionCreate(Sender);

end;

procedure Tf_main.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
  rFiles.SaveToFile(path+'recent');
end;

procedure Tf_main.edit_findKeyDown(Sender: TObject; var Key: word; Shift: TShiftState);
begin
  if key = 13 then
  begin
    frDlg.FindText := edit_find.Text;
    frDlgFind(Sender);
    Key := 0; //Что бы не пищало
  end;
end;

procedure Tf_main.Edit1Change(Sender: TObject);
  var
  i: integer;
begin
  for i := 0 to tv_db.Items.Count - 1 do
    if Pos(AnsiUpperCase(Edit1.Text),AnsiUpperCase(tv_db.Items[i].Text)) <> 0 then
    begin
      tv_db.Selected := tv_db.Items[i];
     // tv_db.SetFocus;
      //Edit1.Text := '';
      break;
    end;
end;

procedure Tf_main.Edit1Click(Sender: TObject);
begin
  if Edit1.Text = Localize('Search...') then Edit1.Text:='';
end;

procedure Tf_main.Edit1EditingDone(Sender: TObject);
begin

end;

procedure Tf_main.FormCloseQuery(Sender: TObject; var CanClose: boolean);
var
  i, ii: integer;
begin
  for I := 0 to pc_right.ControlCount - 1 do
    if pc_right.Controls[I] is TEditTabSheet then
    begin
      if TEditTabSheet(pc_right.Controls[i]).Edt.Modified = True then
      begin
        case MessageDlg(Caption, Localize('Save changes?'),
            mtConfirmation, [mbYes, mbYesToAll, mbNo, mbNoToAll, mbCancel], 0) of
          mrYes:
          begin
            if TEditTabSheet(pc_right.Controls[i]).Edt.FileName = '' then
            begin
              if sDlg.Execute then
                TEditTabSheet(pc_right.Controls[i]).Edt.Lines.SaveToFile(sDlg.FileName);
            end
            else
              TEditTabSheet(pc_right.Controls[i]).Edt.Lines.SaveToFile(sDlg.FileName);
          end;
          mrCancel:
          begin
            CanClose := False;
            Exit;
          end;
          mrNoToAll:
          begin
            CanClose := True;
            Exit;
          end;
          mrYesToAll:
          begin
            for ii := 0 to pc_right.ControlCount - 1 do
              if (pc_right.Controls[ii] is TEditTabSheet) and
                (TEditTabSheet(pc_right.Controls[ii]).Edt.Modified = True) then
              begin
                if TEditTabSheet(pc_right.Controls[ii]).Edt.FileName = '' then
                begin
                  if sDlg.Execute then
                    TEditTabSheet(pc_right.Controls[ii]).Edt.Lines.SaveToFile(
                      sDlg.FileName);
                end
                else
                  TEditTabSheet(pc_right.Controls[ii]).Edt.Lines.SaveToFile(
                    TEditTabSheet(pc_right.Controls[i]).Edt.FileName);
              end;
            CanClose := True;
            Exit;
          end;
        end;
      end;

    end;

end;

procedure Tf_main.mHelpaboutClick(Sender: TObject);
begin
 f_about.ShowModal;
end;

procedure Tf_main.mProjectCloseClick(Sender: TObject);
begin
  case MessageDlg(Caption, Localize('Save project'+' '+PrjManager.Strings[6]+'?'),
          mtConfirmation, [mbYes, mbNo, mbCancel], 0) of
        mrYes:
        begin
          PrjManager.SaveToFile(PrjManager.FileName);
          mFileCloseAllClick(Sender);
          PrjManager.Free;
        end;
        mrNo:
        begin
          mFileCloseAllClick(Sender);
          PrjManager.Free;
        end;
        mrCancel:
        begin
          Exit;
        end;
      end;
  pm_tabAdd2Prj.Visible:=False;
end;

procedure Tf_main.mProjectNewClick(Sender: TObject);
begin
     if not assigned(PrjManager) then
     begin
      PrjManager := TPrjManager.Create;
      mFileCloseAllClick(Sender);
     end
    else
    begin
      case MessageDlg(Caption, Localize('Save project'+PrjManager.Strings[6]+'?'),
          mtConfirmation, [mbYes, mbNo, mbCancel], 0) of
        mrYes:
        begin
          PrjManager.SaveToFile(PrjManager.FileName);
          PrjManager.Clear;
        end;
        mrNo:
        begin
          mFileCloseAllClick(Sender);
          PrjManager.Clear;
        end;
        mrCancel:
        begin
          Exit;
        end;
      end;

    end;
   sDlg.FilterIndex := 4;
       sDlg.Title:=Localize('New project');
       if f_newprgdlg.ShowModal = mrOk then
  begin
      if sDlg.Execute then
      begin
        PrjManager.Add('/*Connection*/');
        PrjManager.Add(f_newprgdlg.cb_host.Text);  //host name
        PrjManager.Add(f_newprgdlg.ed_port.Text);  //port
        PrjManager.Add(f_newprgdlg.ed_db.Text);    //database name
        PrjManager.Add(f_newprgdlg.cb_login.Text); //user name
        PrjManager.Add('/*Project name*/');
        PrjManager.Add(f_newprgdlg.ed_prjname.Text); //Project name
        PrjManager.Add('/*Files*/');
        PrjManager.SaveToFile(sDlg.FileName);
        PrjManager.FileName := (sDlg.FileName);
        OpenProj(Sender,PrjManager.FileName, mNew) ;

       end;

  end;

end;

procedure Tf_main.mProjectOpenClick(Sender: TObject);
begin
  oDlg.FilterIndex:=4;
  if oDlg.Execute then OpenProj(Sender,oDlg.FileName, mOpen);

end;

procedure Tf_main.mRunExecuteClick(Sender: TObject);
var i: integer;
    t: Real;
  Tab: TeditTabSheet;
           //!!!!!!!!!!сделать запуск отдельным потоком!!!!!!!
begin
  if pc_right.PageCount < 1 then Exit;
  Tab := (pc_right.ActivePage as TeditTabSheet);
  Tab.Query.SQL.Text:=Tab.Edt.Text;
   try
  t:=GetTickCount;
  Tab.Query.Open;
  application.ProcessMessages;
  t:=GetTickCount-t;
  except
   on e: exception do
     begin
       Tab.MessageTS.Show;
       Tab.Msg.Items.Add(TimeToStr(Time)+' || '+e.Message);
       Tab.Query.Cancel;
       Exit;
     end;
    end;
  if Tab.Query.FieldCount>0 then
  begin
  Tab.GridTS.Show ;
  StatusBar.Panels[0].Text:=IntToStr(Tab.Query.RecordCount)+' rows '+
  FloatToStr(t/1000)+Localize(' sec.');
  end
  else
  begin
      Tab.MessageTS.Show;
      Tab.Msg.Items.Add(TimeToStr(Time)+' || '+Localize('Query returned successfully with no result in')+' '+FloatToStr(t/1000)+Localize(' sec.') );
  end;


end;

procedure Tf_main.mRunStopClick(Sender: TObject);
var
  tab: TEditTabSheet;
begin
   Tab := (Sender as TEditTabSheet);
   //Tab.Query.Close;
end;

procedure Tf_main.mServiceIdeParClick(Sender: TObject);
begin

end;

procedure Tf_main.mViewFSClick(Sender: TObject);
begin
   if f_main.BorderStyle = bsSizeable then
      begin
       opt.FormHeight:=Height;
       opt.FormWidth:=Width;
       opt.FormLeft:=Left;
       opt.FormTop:=Top;
       BorderStyle:=bsNone;
       FormStyle:=fsStayOnTop;
       Height:=Screen.Height;
       Width:=Screen.Width;
       Left:=0;
       Top:=0;
      end else
      begin
       Height:=opt.FormHeight;
       Width:=opt.FormWidth;
       Left:=opt.FormLeft;
       Top:=opt.FormTop;
       BorderStyle:=bsSizeable;
       FormStyle:=fsNormal;

      end;
end;

procedure Tf_main.pc_rightChange(Sender: TObject);
begin

end;

procedure Tf_main.pc_rightCloseTabClicked(Sender: TObject);
var
  tab: TEditTabSheet;
begin
  Tab := (Sender as TEditTabSheet);
  if Tab.Edt.Modified = True then
  begin
    case MessageDlg(Caption, Localize('Save changes?'),
        mtConfirmation, [mbYes, mbNo, mbCancel], 0) of
      mrYes:
      begin
        if tab.Edt.FileName = '' then
        begin
          if sDlg.Execute then
            Tab.Edt.Lines.SaveToFile(sDlg.FileName);
        end
        else
          Tab.Edt.Lines.SaveToFile(Tab.Edt.FileName);
      end;
      mrNo:
      begin
        Tab.Free;
      end;
      mrCancel:
      begin
        Exit;
      end;
    end;

  end
  else
    tab.Free;

end;


procedure Tf_main.pc_rightContextPopup(Sender: TObject; MousePos: TPoint;
  var Handled: boolean);
begin

end;

procedure Tf_main.pc_rightMouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: integer);
var
  SelectPoint: TPoint;
begin
  SelectPoint.x := X;
  SelectPoint.y := Y;
  pc_right.ActivePageIndex := pc_right.TabIndexAtClientPos(SelectPoint);

end;


procedure Tf_main.pm_dbePopup(Sender: TObject);
var i: integer;
    mi: array[0..10] of TMenuItem;
    objtype, c: string;
begin

 for i:=pm_dbe.Items.Count-1 downto 1 do
      begin
       pm_dbe.Items.Delete(i);
      end;

 for i:=0 to 5 do if tv_db.Selected.HasChildren = true then exit;


 objtype:=tv_db.Selected.Parent.Text;

 if (objtype = Localize('Tables')) or (objtype = Localize('Views')) then
     begin
        mi[8]:= TMenuItem.Create(self);
        mi[8].Caption := ('-');
        pm_dbe.Items.Add(mi[8]);

        mi[1]:= TMenuItem.Create(self);
        mi[1].Caption := Localize('Query Data');
        pm_dbe.Items.Add(mi[1]);
        mi[1].OnClick:=@GetSelectSQL; ;
      if objtype <> Localize('Views') then
         begin
          mi[2]:= TMenuItem.Create(self);
          mi[2].Caption := Localize('Edit Data');
          pm_dbe.Items.Add(mi[2]);
          mi[2].OnClick:=@GetSelectSQL; ;
        end;
        mi[3]:= TMenuItem.Create(self);
        mi[3].Caption := Localize('Scripts');
        pm_dbe.Items.Add(mi[3]);

        mi[4]:= TMenuItem.Create(Self);
        mi[4].Caption := 'CREATE SQL';
        mi[3].Add(mi[4]);

        mi[5]:= TMenuItem.Create(self);
        mi[5].Caption := 'SELECT SQL';
        mi[3].Add(mi[5]);
        mi[5].OnClick:=@GetSelectSQL;

        mi[9]:= TMenuItem.Create(self);
        mi[9].Caption := ('-');
        pm_dbe.Items.Add(mi[9]);

        mi[6]:= TMenuItem.Create(self);
        mi[6].Caption := Localize('Drop');
        pm_dbe.Items.Add(mi[6]);

        mi[7]:= TMenuItem.Create(self);
        mi[7].Caption := ('-');
        pm_dbe.Items.Add(mi[7]);

        mi[10]:= TMenuItem.Create(self);
        mi[10].Caption := Localize('Disable Triggers');
        pm_dbe.Items.Add(mi[10]);

        mi[8]:= TMenuItem.Create(self);
        mi[8].Caption := Localize('Properties');
        pm_dbe.Items.Add(mi[8]);
      end;

 if (objtype = Localize('Functions')) or (objtype = Localize('Trigger Functions')) then
      begin
        mi[1]:= TMenuItem.Create(self);
        mi[1].Caption := ('-');
        pm_dbe.Items.Add(mi[1]);

        mi[2]:= TMenuItem.Create(self);
        mi[2].Caption := Localize('New Function');
        pm_dbe.Items.Add(mi[2]);

        mi[3]:= TMenuItem.Create(self);
        mi[3].Caption := '-';
        pm_dbe.Items.Add(mi[3]);

        mi[4]:= TMenuItem.Create(self);
        mi[4].Caption := Localize('View Function');
        pm_dbe.Items.Add(mi[4]);
        mi[4].OnClick:=@GetDef_funct;

        mi[5]:= TMenuItem.Create(self);
        mi[5].Caption := Localize('Edit Function');
        pm_dbe.Items.Add(mi[5]);
        mi[5].OnClick:=@GetDef_funct;

        mi[6]:= TMenuItem.Create(self);
        mi[6].Caption := Localize('Drop Function');
        pm_dbe.Items.Add(mi[6]);

        mi[7]:= TMenuItem.Create(self);
        mi[7].Caption := '-';
        pm_dbe.Items.Add(mi[7]);

        mi[8]:= TMenuItem.Create(self);
        mi[8].Caption := Localize('Properties');
        pm_dbe.Items.Add(mi[8]);
      end;
    if objtype = Localize('Sequences') then
      begin
        mi[1]:= TMenuItem.Create(self);
        mi[1].Caption := Localize('New');
        pm_dbe.Items.Add(mi[1]);

        mi[3]:= TMenuItem.Create(self);
        mi[3].Caption := Localize('Create Script');
        pm_dbe.Items.Add(mi[3]);

        mi[2]:= TMenuItem.Create(self);
        mi[2].Caption := ('-');
        pm_dbe.Items.Add(mi[2]);

        mi[3]:= TMenuItem.Create(self);
        mi[3].Caption := Localize('Properties');
        pm_dbe.Items.Add(mi[3]);
       end;
     if objtype = Localize('Triggers') then
      begin
        mi[1]:= TMenuItem.Create(self);
        mi[1].Caption := Localize('New');
        pm_dbe.Items.Add(mi[1]);

        mi[2]:= TMenuItem.Create(self);
        mi[2].Caption := Localize('Create Script');
        pm_dbe.Items.Add(mi[2]);
        mi[2].OnClick:=@GetDefTg;

      end;


end;

procedure Tf_main.pm_dbe_refreshClick(Sender: TObject);
begin
  GetDbObject();
end;

procedure Tf_main.pm_gridExportClick(Sender: TObject);
var Tab: TeditTabSheet;
begin
 //Export data in csv
    Tab := (pc_right.ActivePage as TeditTabSheet);
       try

    if (sDlgExp.Execute = true) and
     (length(sDlgExp.FileName) > 0) then
      begin
         SaveAsCSV(sDlgExp.FileName,Tab.Query);
      end;
  finally
  end;
end;

procedure Tf_main.pm_gridPopup(Sender: TObject);
var Tab: TeditTabSheet;
begin
     Tab := (pc_right.ActivePage as TeditTabSheet);
    if Tab.Query.IsEmpty=True then pm_gridExport.Enabled:=False
    else pm_gridExport.Enabled:=True;
end;

procedure Tf_main.pm_msgCopyAllClick(Sender: TObject);
var Tab: TeditTabSheet;
begin
  Tab := (pc_right.ActivePage as TeditTabSheet);
  if Tab.Msg.Count<1 then exit;
  ClipBoard.AsText:=Tab.Msg.Items.Text;

end;

procedure Tf_main.pm_EdtCopyClick(Sender: TObject);
var  Tab: TeditTabSheet;
begin
  Tab := (pc_right.ActivePage as TeditTabSheet);
  Tab.Edt.CopyToClipboard;

end;

procedure Tf_main.pm_EdtCutClick(Sender: TObject);
var  Tab: TeditTabSheet;
begin
  Tab := (pc_right.ActivePage as TeditTabSheet);
  Tab.Edt.CutToClipboard;
end;

procedure Tf_main.pm_EdtPasteClick(Sender: TObject);
var  Tab: TeditTabSheet;
begin
  Tab := (pc_right.ActivePage as TeditTabSheet);
  Tab.Edt.PasteFromClipboard;
end;

procedure Tf_main.pm_msgClearClick(Sender: TObject);
var  Tab: TeditTabSheet;
begin
  Tab := (pc_right.ActivePage as TeditTabSheet);
  Tab.Msg.Clear;

end;

procedure Tf_main.pm_msgCopyClick(Sender: TObject);
var Tab: TeditTabSheet;
begin
  Tab := (pc_right.ActivePage as TeditTabSheet);
  if Tab.Msg.Count<1 then exit;
  ClipBoard.AsText:=Tab.Msg.Items[Tab.Msg.ItemIndex];
end;

procedure Tf_main.pm_PrjAddClick(Sender: TObject);
begin
  if oDlg.Execute then
    begin
      with lv_prj.Items.Add do
       begin
        Caption := oDlg.FileName;
        ImageIndex := 16;
       end;
    end;
   CreateTab(Sender, mOpen, False, oDlg.FileName);
end;

procedure Tf_main.pm_prjOpenClick(Sender: TObject);
begin
   CreateTab(Sender, mOpen, False, lv_prj.Selected.Caption);
end;

procedure Tf_main.pm_tabAdd2PrjClick(Sender: TObject);
var Tab: TeditTabSheet;
begin
     Tab := (pc_right.ActivePage as TeditTabSheet);
     mFileSaveClick(Sender);
     with lv_prj.Items.Add do
      begin
      Caption := Tab.Edt.FileName;
      ImageIndex := 16;
      end;
end;

procedure Tf_main.pm_TabCloseClick(Sender: TObject);
begin
  pc_rightCloseTabClicked(pc_right.ActivePage);
end;


procedure Tf_main.CreateTab(Sender: TObject; Mode: TModeCreate; RO: boolean;
  FileName: string);
var
  ts_msg, ts_grid: TTabSheet;
  tab: TEditTabSheet;
  edt: TpgEditor;
  spl: TSplitter;
  pc_dbg: TPageControl;
  lb_msg: TListBox;
  dbnav: TDbNavigator;
  grid: TDbGrid;
  Query: TzQuery;
  DSrc:    TDataSource;

begin
  tab := TEditTabSheet.Create(pc_right);//New TabSheet
  tab.Parent := pc_right;
  if Mode = mNew then
  tab.Caption := 'New ' + IntToStr(pc_right.PageCount);
  tab.PageControl.ActivePage := tab;
  tab.ImageIndex := 15;
  edt := TpgEditor.Create(tab); //Editor
  edt.Parent := tab;
  edt.Align := alClient;
  edt.Highlighter := Highlighter;
  edt.PopupMenu := pm_Edt;
  edt.Font.Name:=opt.FontName;
  edt.Font.Size:=opt.FontSize;
  edt.Gutter.Visible:=opt.Gutter;
  SQLCompletion.AddEditor(Edt);
  Edt.OnKeyPress:=@SQLComplKeyPress;
  if opt.AA=True then edt.Font.Quality:=fqCleartype;
  tab.Edt := edt;
  pc_dbg := TPageControl.Create(tab); //Debug PageControl
  pc_dbg.Parent := tab;
  pc_dbg.Align := alBottom;
  pc_dbg.Height := round(tab.Height / 3);
  spl := TSplitter.Create(tab);     //splitter
  spl.Parent := tab;
  spl.Align := alBottom;
  ts_Msg := TTabSheet.Create(pc_dbg);
  ts_Msg.Parent := pc_dbg;
  ts_Msg.Caption := Localize('Messages');
  lb_msg := TListBox.Create(ts_Msg);
  lb_msg.Parent := ts_Msg;
  lb_msg.Align := alClient;
  tab.Msg:=lb_msg;
  ts_grid := TTabSheet.Create(pc_dbg);
  ts_grid.Parent := pc_dbg;
  ts_grid.Caption := Localize('Grid');

  grid := TDbGrid.Create(ts_grid);
  grid.Parent := ts_grid;
  grid.Align := alClient;
 // grid.ReadOnly:=True;
 // grid.AutoFillColumns:=True;
  grid.Options:=grid.Options+[dgAutoSizeColumns];
  tab.GridTS:=ts_grid;
  tab.MessageTS:=ts_msg;
  Tab.GridTS.PopupMenu:=pm_grid;
  //Скорее всего временно
  Query:=TzQuery.Create(Self);
  Query.Connection:=zConn;
  Query.ParamCheck:=False;
  Tab.Query:=Query;

  Dsrc:=TDataSource.Create(Self);
  DSrc.DataSet:=Query;
  grid.DataSource:=Dsrc;

  dbnav := TDbNavigator.Create(ts_Grid);
  dbnav.Parent := ts_Grid;
  dbnav.Align := alTop;
  Tab.DBNavigator:=dbnav;
  dbnav.enabled:=False;
  dbnav.DataSource:=DSrc;
  Query.ReadOnly:=True;
  Tab.Msg.PopupMenu:=pm_msg;

    if Mode = mOpen then
  begin
    edt.Lines.LoadFromFile(FileName);
    tab.Caption := ExtractFileName(FileName);
    edt.FileName := FileName;
    RecentAdd(FileName);
  end;
  edt.SetFocus;
end;

procedure Tf_main.pm__prjRmClick(Sender: TObject);
begin
  lv_prj.Selected.Delete;
end;

procedure Tf_main.SetLng();
var i: integer;
begin
  LoadLocalize(Language);
  mEdiOpt.Caption := Localize('Options');
  pm_EdtPaste.Caption := Localize('Paste');
  pm_EdtCopy.Caption := Localize('Copy');
  pm_EdtCut.Caption := Localize('Cut');
  pm_TabClose.Caption := Localize('Close');
  mHelpabout.Caption := Localize('About');
  mHelpHelp.Caption := Localize('Help');
  mEdit.Caption := Localize('Edit');
  mEditUndo.Caption := Localize('Undo');
  mEditRedo.Caption := Localize('Redo');
  mEditCut.Caption := Localize('Cut');
  mEditCopy.Caption := Localize('Copy');
  mEditPaste.Caption := Localize('Paste');
  mEditSearch.Caption := Localize('Search and replace');
  mEditGoToString.Caption := Localize('Go to string');
  mHelpBags.Caption := Localize('Send bugreport');
  mHelp.Caption := Localize('Help');
  mProjectClose.Caption := Localize('Close project');
  mProjectRecent.Caption := Localize('Recent');
  mProjectOpen.Caption := Localize('Open project');
  mView.Caption := Localize('View');
  mProjectNew.Caption := Localize('New project');
  mProject.Caption := Localize('Project');
  mFileConnectionClose.Caption := Localize('Close connection');
  mFileExit.Caption := Localize('Exit');
  mFilePrint.Caption := Localize('Print');
  mFileOpen.Caption := Localize('Open');
  mFileNew.Caption := Localize('New SQL');
  mFileNewFile.Caption := Localize('From template');
  mFileCloseAll.Caption := Localize('Close all');
  mFileClose.Caption := Localize('Close');
  mFileConnection.Caption := Localize('New connection');
  mFileSaveAll.Caption := Localize('Save all');
  mFileRecentFiles.Caption := Localize('Recent');
  mFileSaveAs.Caption := Localize('Save as...') ;
  mFileSave.Caption := Localize('Save') ;
  mFile.Caption := Localize('File');
  mRun.Caption:=Localize('Run');
  mRunExecute.Caption:=Localize('Execute');
  mRunStop.Caption:=Localize('Stop');
  ts_ProjectExplorer.Caption:=Localize('Project inspector');
  ts_dbexplorer.Caption:=Localize('Database');
  pm_msgCopy.Caption:=Localize('Copy');
  pm_msgCopyAll.Caption:=Localize('Copy all');
  pm_msgClear.Caption:=Localize('Clear');
  pm_gridExport.Caption:=Localize('Export to')+' csv';


  for i := 0 to pc_right.ControlCount - 1 do
    if (pc_right.Controls[i] is TEditTabSheet) then
    begin
       TEditTabSheet(pc_right.Controls[i]).MessageTS.Caption:=Localize('Messages');
       TEditTabSheet(pc_right.Controls[i]).GridTS.Caption:=Localize('Grid');
end;
  oDlg.Filter:=Localize('SQL Script')+'|*.sql|'+Localize('Program')+
   '|*.pgfnc|'+Localize('TCL Script')+'|*.tcl|'+
   Localize('Project')+'|*.pgprg|'+Localize('All files')+'|*.*|';
  sDlg.Filter:=oDlg.Filter;

end;

procedure Tf_main.CreateIni();
var cfg: TIniFile;
begin
      if not DirectoryExists(path) then CreateDir(path);
      cfg:=TIniFile.Create(path+'pgdev.cfg');
      cfg.DeleteKey('Default', 'Language');
      cfg.WriteString('Default', 'Language', 'english.lng');
      cfg.DeleteKey('Editor', 'FontName');
      cfg.WriteString('Editor', 'FontName', 'Consolas');
      cfg.DeleteKey('Editor', 'FontSize');
      cfg.WriteInteger('Editor', 'FontSize', 10);
      cfg.DeleteKey('Editor', 'Gutter');
      cfg.WriteBool('Editor', 'Gutter', False);
      cfg.DeleteKey('Editor', 'antialiasing');
      cfg.WriteBool('Editor', 'antialiasing', False);
      cfg.DeleteKey('Completion', 'DBOCopml');
      cfg.WriteInteger('Completion', 'DBOCopml', 0);
      cfg.DeleteKey('Completion', 'SQLCompl');
      cfg.WriteInteger('Completion', 'SQLCompl', 0);
      cfg.Free;
end;

procedure Tf_main.ReadIni();
var cfg, rf: TIniFile;
    f: TextFile;
begin
   if not assigned(opt) then opt:=TOptions.Create;
   {$IFDEF LINUX}
   path:=Home:=GetEnvironmentVariable('HOME')+DirectorySeparator+
   '.pgstudio'+DirectorySeparator;
    {$endif}
 {$IFDEF Windows}
   path:=GetEnv('USERPROFILE')+DirectorySeparator+
   '.pgstudio'+DirectorySeparator;
  {$endif}
 if not FileExists(path+'pgdev.cfg') then CreateIni;
  cfg:=TIniFile.Create(path+'pgdev.cfg');
  opt.FontName:=cfg.ReadString ('Editor', 'FontName', '');
  opt.FontSize:=cfg.ReadInteger('Editor', 'FontSize', 0);
  opt.AA:=cfg.ReadBool('Editor', 'antialiasing', false);
  opt.Gutter:=cfg.ReadBool('Editor', 'Gutter', false);
  Language:=cfg.ReadString ('Default', 'Language', '');
  opt.DBOCompletion:=cfg.ReadBool('Completion','DBOCopml',false);
  opt.SQLCompletion:=cfg.ReadBool('Completion','SQLCopml',false);
  cfg.Free;
  //Load recents files
   if not FileExists(path+'recent') then
        begin
        rf:=TiniFile.Create(path+'recent');
        rf.WriteString('','','');
        rf.Free;

        end;

   rFiles:=TStringList.Create;
   Rfiles.LoadFromFile(path+'recent');

   //Highlighter
   Highlighter:=TSynSQLSyn.Create(Self);
   Highlighter.LoadFromFile('SQLSyn.cfg');
   Highlighter.SQLDialect:=sqlOracle; //Пока своего нет...

end;

procedure Tf_main.SetOptions();
var i: integer;
begin
  for i := 0 to pc_right.ControlCount - 1 do
    if (pc_right.Controls[i] is TEditTabSheet) then
    begin
       TEditTabSheet(pc_right.Controls[i]).Edt.Font.Name:=opt.FontName;
       TEditTabSheet(pc_right.Controls[i]).Edt.Font.Size:=opt.FontSize;
       TEditTabSheet(pc_right.Controls[i]).Edt.Gutter.Visible:=opt.Gutter;
    end;

end;

procedure Tf_main.OpenProj(Sender: TObject; FileName: string; Mode: TModeCreate);
var i: integer;
begin
  Case Mode of
  mOpen:
   begin
     if not assigned(PrjManager) then
       begin
         PrjManager := TPrjManager.Create;
         mFileCloseAllClick(Sender);
         PrjManager.LoadFromFile(FileName);
       end
       else
       begin
        case MessageDlg(Caption, Localize('Save project'+' '+PrjManager.Strings[6]+'?'),
          mtConfirmation, [mbYes, mbNo, mbCancel], 0) of
          mrYes:
            begin
              PrjManager.SaveToFile(PrjManager.FileName);
              PrjManager.Clear;
            end;
          mrNo:
            begin
              mFileCloseAllClick(Sender);
              PrjManager.Clear;
            end;
          mrCancel:
            begin
             Exit;
            end;
           end;
        end;

     end;
   end;
  Caption:=Caption+' '+PrjManager.Strings[6];
  f_lp.cb_host.Text:=PrjManager.Strings[1];
  f_lp.ed_port.Text:=PrjManager.Strings[2];
  f_lp.ed_db.Text:=PrjManager.Strings[3];
  f_lp.ed_login.Text:=PrjManager.Strings[4];
  mFileConnectionClick(Sender);
  for i:=8 to PrjManager.Count-1 do
    begin
     lv_prj.Items.Add.Caption:=PrjManager.Strings[i];
    end;
    pm_tabAdd2Prj.Enabled:=true;
    pm_tabAdd2Prj.Visible:=True;
end;


function Tf_main.Connect(): boolean;
begin
  if not Assigned(f_lp)then f_lp:=Tf_lp.Create(Self);
  if f_lp.ShowModal = mrOk then
    begin
      zconn.Connected:=False;
      zconn.HostName:=f_lp.cb_host.Text;
      zconn.Port:=StrToInt(f_lp.ed_port.Text);
      zconn.Database:=f_lp.ed_db.Text;
      zconn.User:=f_lp.ed_login.Text;
      zconn.Password:=f_lp.ed_pass.Text;
      try
      zconn.Connected:=True;
      except
        on e: exception do
          begin
           ShowMessage(e.Message);
           Exit;
          end;
        end;
      end else
    begin
        zconn.Connected:=False;
        mRunExecute.Enabled:=False;
        mRunStop.Enabled:=False;
        tbtStop.Enabled:=False;
        tbtRun.Enabled:=False;
        Result:=False;
        Exit;
    end;
    // if zconn.Connected=True then Result:=True else Result:=False;
    Result:=True ;
     //Перенести куда нибудь, выполнять только в случае connect=True;
     GetDbObject();
    // FreeAndNil(f_lp);
end;


procedure Tf_main.GetDbObject();
var q: TZQuery;
    ii: integer;
    //Временно...
begin
  q:=TZQuery.Create(Self);
  q.Connection:=zconn;
  tv_db.Items.Clear;
  //Tables list
  tv_db.Items.Add(nil, Localize('Tables')).ImageIndex:=34;
  q.SQL.Text:='select table_name, table_schema from information_schema.tables '+
    'where table_schema not in ('+#39+'pg_catalog'+#39+','#39+'information_schema'+#39+')'+'order by table_name' ;
  q.Open;
    while not q.Eof do
      begin
        tv_db.Items.AddChild(tv_db.Items.Item[0],q.FieldByName('table_schema').AsString+'.'+q.FieldByName('table_name').AsString).ImageIndex:=33;

        q.Next;
      end;
   q.Close;
   q.SQL.Clear;



   //Views list
   q.SQL.Text:='select table_name, table_schema from information_schema.views '+
        'where table_schema not in ('+#39+'pg_catalog'+#39+','#39+'information_schema'+#39+')'+'order by table_name' ;
   q.Open;
   tv_db.Items.Add(nil, Localize('Views')).ImageIndex:=34;
   ii:=tv_db.Items.Count-1;
    while not q.Eof do
      begin
        tv_db.Items.AddChild(tv_db.Items.Item[ii], q.FieldByName('table_schema').AsString+'.'+q.FieldByName('table_name').AsString).ImageIndex:=36;
        q.Next;
      end;
   q.Close;
   q.SQL.Clear;
   //Sequences list
   q.SQL.Text:='select sequence_name, sequence_schema from information_schema.sequences order by sequence_name';
   q.Open;
   tv_db.Items.Add(nil, Localize('Sequences')).ImageIndex:=34;
   ii:=tv_db.Items.Count-1;
    while not q.Eof do
      begin
        tv_db.Items.AddChild(tv_db.Items.Item[ii], q.FieldByName('sequence_schema').AsString+'.'+q.FieldByName('sequence_name').AsString).ImageIndex:=37;
        q.Next;
      end;
   q.Close;
   q.SQL.Clear;
    //triggers list
   q.SQL.Text:='select trigger_name from information_schema.triggers order by trigger_name';
   q.Open;
   tv_db.Items.Add(nil, Localize('Triggers')).ImageIndex:=34;
   ii:=tv_db.Items.Count-1;
    while not q.Eof do
      begin
        tv_db.Items.AddChild(tv_db.Items.Item[ii], q.FieldByName('trigger_name').AsString).ImageIndex:=38;
        q.Next;
      end;
   q.Close;
   q.SQL.Clear;

   //trigger functions list --Позднее приделать к таблицам
    q.SQL.Text:='select routine_name from information_schema.routines '+
     'where routine_schema not in ('+#39+'pg_catalog'+#39+','#39+'information_schema'+#39+') and data_type ='+#39+'trigger'+#39+'order by routine_name';
   q.Open;
   tv_db.Items.Add(nil, Localize('Trigger Functions')).ImageIndex:=34;
   ii:=tv_db.Items.Count-1;
    while not q.Eof do
      begin
        tv_db.Items.AddChild(tv_db.Items.Item[ii], q.FieldByName('routine_name').AsString).ImageIndex:=35;
        q.Next;
      end;
   q.Close;
   q.SQL.Clear;


   //function list
     q.SQL.Text:='select routine_name from information_schema.routines '+
     'where routine_schema not in ('+#39+'pg_catalog'+#39+','#39+'information_schema'+#39+') and data_type !='+#39+'trigger'+#39+'order by routine_name';
   q.Open;
   tv_db.Items.Add(nil, Localize('Functions')).ImageIndex:=34;
   ii:=tv_db.Items.Count-1;
    while not q.Eof do
      begin
        tv_db.Items.AddChild(tv_db.Items.Item[ii], q.FieldByName('routine_name').AsString).ImageIndex:=35;
        q.Next;
      end;
   q.Close;
   q.SQL.Clear;
 q.Free;
end;



procedure Tf_main.tv_dbDblClick(Sender: TObject);
begin

end;

//Crete recent file menu
procedure Tf_main.RecentLoad();
var i: integer;
    mi: array[0..9] of TMenuItem;
begin
if  rFiles.Count<1 then exit;
for i:=mFileRecentFiles.Count-1 downto 0 do
  begin
     mFileRecentFiles.Delete(i);
  end;
for i:=0 to rFiles.Count-1 do
  begin
     mi[rFiles.Count-1-i] := TMenuItem.Create(self);
     mi[rFiles.Count-1-i].Caption := rFiles.Strings[rFiles.Count-i-1];
     mi[rFiles.Count-1-i].OnClick:=@RecentOpen;
     mFileRecentFiles.Add(mi[rFiles.Count-1-i]);
  end;
end;

//Open recent files
procedure Tf_main.RecentOpen(Sender: TObject);
begin
   if SheetExist((Sender as TMenuItem).Caption) = true then Exit;
   CreateTab(sender, mOpen, False,(Sender as TMenuItem).Caption);
end;

//add recent files
procedure Tf_main.RecentAdd(FileName: string);
begin
 if rFiles.IndexOf(FileName)>=0 then
   begin
      rFiles.Delete(rFiles.IndexOf(FileName));
   end;
 if rFiles.Count =10 then  rFiles.Delete(0);
 rFiles.Add(FileName);
 RecentLoad();
end;

function Tf_main.SheetExist(FileName: string): boolean;
var i:integer;
begin
  result:=false;
   for i:=0 to pc_right.ControlCount-1 do
     if (pc_right.Controls[i] is TEditTabSheet) then
     if TEditTabSheet(pc_right.Controls[i]).edt.FileName=FileName then
       begin
          TEditTabSheet(pc_right.Controls[i]).Show;
          TEditTabSheet(pc_right.Controls[i]).Msg.Items.Add(TimeToStr(Time)+' || '+Localize('File already open'));
          result:=true;
          exit;
       end;
end;


procedure Tf_main.GetSelectSQL(Sender: TObject);
 var Tab: TEditTabSheet;
begin
   CreateTab(Sender, mNew, False, '');
   Tab := (pc_right.ActivePage as TeditTabSheet);
   Tab.Edt.Lines.Add('select * from '+tv_db.Selected.Text+' t');
   if (Sender as TMenuItem).Caption = Localize('Query Data') then mRunExecuteClick(Sender);
   if (Sender as TMenuItem).Caption = Localize('Edit Data') then
    begin
     Tab.Query.ReadOnly:=False;
     Tab.DBNavigator.Enabled:=True;
     mRunExecuteClick(Sender);
    end;
end;


procedure Tf_main.GetDefTg(Sender: TObject);
 var q: TZQuery;
    Tab: TEditTabSheet;
begin
 q:=TZQuery.Create(Self);
 q.SQL.Text:='SELECT pg_get_triggerdef(oid)'
	    +' FROM pg_trigger'
 	    +' WHERE tgname = '+#39+tv_db.Selected.Text+#39;
 q.Connection:=zconn;
 q.Open;
 CreateTab(Sender, mNew, False, '');
 Tab := (pc_right.ActivePage as TeditTabSheet);
 Tab.Edt.Text:=q.FieldByName('pg_get_triggerdef').Value;
 q.Close;
 q.Free;
end;

{SQL completion}
procedure Tf_main.SQLCompletionCreate(Sender: TObject);
begin
  SQLComplList:=TStringList.Create;
  SQLComplList.LoadFromFile('sqlcomp');
  SQLCompletion := TSynCompletion.Create(Self);
  SQLCompletion.CaseSensitive := False;
  SQLCompletion.OnSearchPosition := @DoSearchPosition;
  SQLCompletion.ShowSizeDrag := True;
  SQLCompletion.DoubleClickSelects := True;
end;

procedure Tf_main.SQLComplKeyPress(Sender: TObject; var Key: char);
begin
 if Opt.SQLCompletion = False then exit;
 if (pc_right.ActivePage as TeditTabSheet).Edt.CaretX<2 then exit;
    if key in ['A'..'Z', 'a'..'z'] then
      begin
        KeyInput.Apply([ssCtrl]);
        KeyInput.Press(VK_SPACE);
        KeyInput.Unapply([ssCtrl]);
      end;
 end;

procedure Tf_main.DoSearchPosition(var APosition: integer);
  procedure Add(s: String);
   begin
     if pos(lowercase(SQLCompletion.CurrentString), lowercase(s)) = 1 then
       SQLCompletion.ItemList.Add(s);
   end;
  var i: integer;
 begin
   SQLCompletion.ItemList.Clear;
   for i:=0 to SQLComplList.Count-1 do
   begin
     Add(SQLComplList.Strings[i]);
   end;

   if SQLCompletion.ItemList.Count > 0 then
     APosition := 0
   else
     APosition := -1;
     if  SQLCompletion.ItemList.Count <= 0 then SQLCompletion.Deactivate;
end;


procedure Tf_main.GetDef_funct(Sender: TObject);
var q: TZQuery;
    Tab: TEditTabSheet;
begin
 q:=TZQuery.Create(Self);
 q.SQL.Text:='select pg_get_functiondef((select oid from pg_proc where proname='+#39+tv_db.Selected.Text+#39+'))';
 q.Connection:=zconn;
 q.Open;
 CreateTab(Sender, mNew, False, '');
 Tab := (pc_right.ActivePage as TeditTabSheet);
 Tab.Edt.Text:=q.FieldByName('pg_get_functiondef').Value;
 if Localize((Sender as TMenuItem).Caption) = Localize('View Function') then
 Tab.Edt.ReadOnly:=True;
 q.Close;
 q.Free;
end;



end.

